/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package main.java.cn.webrx;

import java.io.File;
import java.io.FileInputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: jse2204 - Ex3
 * <p>Powered by webrx On 2022-09-22 17:23:05
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class Ex3 {
    public static void main(String[] args) {
        //判断文件的真实类型  [-1, -40, -1, -31, 16, -64, 69, 120]
        //                 [-1, -40, -1, -31, 16, -64, 69, 120]

        Map<String, Object> map = new HashMap<>();
        map.put("ffd8ffe1", "jpg");
        map.put("fd8ffe0", "png");
        map.put("504b34","zip");
        map.put("52617221","rar");

        System.out.println(getType(new File("c:/abc/Demo.java")));


        //File dir = new File("c:/abc");
        //File[] files = dir.listFiles();
        //for(File f : files){
        //    String fn = f.getName();
        //    String ext = fn.substring(fn.lastIndexOf(".")).toLowerCase();
        //    System.out.printf("%s : %s : %s %n",fn,ext,getHeader(f,10));
        //}
    }

    public static String getType(File file){
        Map<String, String> map = new HashMap<>();
        map.put("ffd8ffe1", "jpg");
        map.put("fd8ffe0", "png");
        map.put("504b34","zip");
        map.put("52617221","rar");
        String header = getHeader(file,4);
        if(map.containsKey(header)){
            return map.get(header);
        }else{
            return "未知文件";
        }

    }

    public static String getHeader(File src, int n) {
        String header = "";
        if (src.isFile()) {
            try (var is = new FileInputStream(src)) {
                byte[] buf = new byte[n];
                is.read(buf);
                StringBuilder sbu = new StringBuilder();
                for (byte b : buf) {
                    sbu.append(String.format("%x", b));
                }
                header = sbu.toString();
            } catch (Exception e) {
            }
        } else {
            header = "不是文件";
        }
        return header;
    }
}
